package com.Dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.news.model.Likes;
import com.database.Mysql;

import java.util.ArrayList;
import java.util.List;

public class LikesDao {
    private SQLiteDatabase db;
    private Mysql dbHelper;

    public LikesDao(Context context) {
        dbHelper = new Mysql(context);
        db = dbHelper.getWritableDatabase();
    }

    // 关闭数据库连接（通常在DAO的销毁方法中调用）
    public void close() {
        db.close();
    }

    // 插入点赞
    public long insertLike(Likes like) {
        ContentValues values = new ContentValues();
        values.put("userid", like.getUserId());
        values.put("newsid", like.getNewsId());
        values.put("commentid", like.getCommentId());
        values.put("createdAt", like.getCreatedAt());

        return db.insert("likes", null, values);
    }

    // 查询所有点赞
    public List<Likes> getAllLikes() {
        List<Likes> likesList = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = db.query("likes", null, null, null, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Likes like = new Likes();

                    int likeIdIndex = cursor.getColumnIndex("likeid");
                    if (likeIdIndex != -1) {
                        like.setLikeId(cursor.getInt(likeIdIndex));
                    } else {
                        Log.e("Database", "Column likeId not found");
                    }

                    int userIdIndex = cursor.getColumnIndex("userid");
                    if (userIdIndex != -1) {
                        like.setUserId(cursor.getInt(userIdIndex));
                    } else {
                        Log.e("Database", "Column userId not found");
                    }

                    int newsIdIndex = cursor.getColumnIndex("newsid");
                    if (newsIdIndex != -1) {
                        like.setNewsId(cursor.getInt(newsIdIndex));
                    } else {
                        Log.e("Database", "Column newsId not found");
                    }

                    int commentIdIndex = cursor.getColumnIndex("commentid");
                    if (commentIdIndex != -1) {
                        like.setCommentId(cursor.getInt(commentIdIndex));
                    } else {
                        Log.e("Database", "Column commentId not found");
                    }

                    int createdAtIndex = cursor.getColumnIndex("createdAt");
                    if (createdAtIndex != -1) {
                        like.setCreatedAt(cursor.getLong(createdAtIndex));
                    } else {
                        Log.e("Database", "Column createdAt not found");
                    }

                    likesList.add(like);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e("Database", "Error fetching likes", e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return likesList;
    }
    //根据userid查询点赞
    public List<Likes> getAllLikesByUserid(int userid) {
        List<Likes> likesList = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = db.query("likes", null, "userid=?", new String[]{String.valueOf(userid)}, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Likes like = new Likes();

                    int likeIdIndex = cursor.getColumnIndex("likeid");
                    if (likeIdIndex != -1) {
                        like.setLikeId(cursor.getInt(likeIdIndex));
                    } else {
                        Log.e("Database", "Column likeId not found");
                    }

                    int userIdIndex = cursor.getColumnIndex("userid");
                    if (userIdIndex != -1) {
                        like.setUserId(cursor.getInt(userIdIndex));
                    } else {
                        Log.e("Database", "Column userId not found");
                    }

                    int newsIdIndex = cursor.getColumnIndex("newsid");
                    if (newsIdIndex != -1) {
                        like.setNewsId(cursor.getInt(newsIdIndex));
                    } else {
                        Log.e("Database", "Column newsId not found");
                    }

                    int commentIdIndex = cursor.getColumnIndex("commentid");
                    if (commentIdIndex != -1) {
                        like.setCommentId(cursor.getInt(commentIdIndex));
                    } else {
                        Log.e("Database", "Column commentId not found");
                    }

                    int createdAtIndex = cursor.getColumnIndex("created_at");
                    if (createdAtIndex != -1) {
                        like.setCreatedAt(cursor.getLong(createdAtIndex));
                    } else {
                        Log.e("Database", "Column createdAt not found");
                    }
                    int isActiveIndex = cursor.getColumnIndex("is_active");
                    if (createdAtIndex != -1) {
                        //布尔值以0 1 形式存储 所以用getInt
                        boolean flag = cursor.getInt(isActiveIndex)!=0;
                        like.setActive(flag);
                    } else {
                        Log.e("Database", "Column createdAt not found");
                    }
                    likesList.add(like); // 添加Likes对象到列表中
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e("Database", "Error fetching likes", e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return likesList;
    }
    // 更新点赞（根据likeId）
    public int updateLike(Likes like) {
        ContentValues values = new ContentValues();
        values.put("is_active",!like.isActive());
        int rowsUpdated = db.update("likes", values, "likeid = ?", new String[]{String.valueOf(like.getLikeId())});
        return rowsUpdated;
    }

    //检查用户是否点赞了新闻
    public boolean isNewsLiked(int userId, int newsId) {
        boolean isLiked = false;
        Cursor cursor = null;
        try{
            String query = "SELECT * FROM likes WHERE userid = ? AND newsid = ?";
            cursor = db.rawQuery(query, new String[]{String.valueOf(userId), String.valueOf(newsId)});
            if (cursor != null && cursor.moveToFirst()) {
                isLiked = true;
            }
        } catch (Exception e) {
            Log.e("Database", "Error checking if news is liked", e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return isLiked;
    }

    // 取消点赞（根据用户ID和新闻ID或评论ID）
    public boolean unlikeNews(int userId, int newsId, int commentId) {
        boolean success = false;
        try {
            String whereClause;
            String[] whereArgs;

            if (newsId != -1) {
                // 取消对新闻的点赞
                whereClause = "userid = ? AND newsid = ?";
                whereArgs = new String[]{String.valueOf(userId), String.valueOf(newsId)};
            } else if (commentId != -1) {
                // 取消对评论的点赞
                whereClause = "userid = ? AND commentid = ?";
                whereArgs = new String[]{String.valueOf(userId), String.valueOf(commentId)};
            } else {
                // 如果newsId和commentId都未指定，则返回失败
                return false;
            }

            // 删除符合条件的点赞记录
            int rowsDeleted = db.delete("likes", whereClause, whereArgs);
            if (rowsDeleted > 0) {
                success = true;
            }
        } catch (Exception e) {
            Log.e("Database", "Error unliking news or comment", e);
        }
        return success;
    }
    //检查用户是否收藏了新闻
    public boolean isNewsFavorited(int userId, int newsId) {
        boolean isFavorited = false;
        Cursor cursor = null;
        try{
            String query = "SELECT * FROM likes WHERE userid = ? AND newsid = ?";
            cursor = db.rawQuery(query, new String[]{String.valueOf(userId), String.valueOf(newsId)});
            if (cursor != null && cursor.moveToFirst()) {
                isFavorited = true;
            }
        } catch (Exception e) {
            Log.e("Database", "Error checking if news is favorited", e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return isFavorited;
    }

    //用户关注作者
    public boolean followAuthor(int userid, int authorid) {
        ContentValues values = new ContentValues();
        values.put("userid", userid);
        values.put("authorid", authorid);

        try {
            db.insert("follows", null, values);
        } catch (Exception e) {
            Log.e("Database", "Error following author", e);
        }
        return false;
    }
    // 用户点赞新闻 也就是插入点赞表
    public boolean likeNews(int userId, int newsId,long created_at) {
        ContentValues values = new ContentValues();
        values.put("userid", userId);
        values.put("newsid", newsId);
        values.put("created_at",created_at);
        try {
            db.insert("likes", null, values);
        } catch (Exception e) {
            Log.e("Database", "Error liking news", e);
        }

        return true;
    }

    // 用户收藏新闻
    public boolean favoriteNews(int userId, int newsId) {
        ContentValues values = new ContentValues();
        values.put("userid", userId);
        values.put("newsid", newsId);

        try {
            db.insert("favorites", null, values);
        } catch (Exception e) {
            Log.e("Database", "Error favoriting news", e);
        }
        return false;
    }




    // 删除点赞（根据likeId）
    public void deleteLike(int likeId) {
        db.delete("likes", "likeid = ?", new String[]{String.valueOf(likeId)});
    }
}

